package com.atguigu.tingshu.account.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.vo.account.RechargeInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@SuppressWarnings({"all"})
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {

	@Autowired
	private RechargeInfoMapper rechargeInfoMapper;

    @Override
    public RechargeInfo getRechargeInfo(String orderNo) {

        LambdaQueryWrapper<RechargeInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RechargeInfo::getOrderNo,orderNo);
        return rechargeInfoMapper.selectOne(queryWrapper);
    }

    /**
     * 保存充值记录
     *
     * @param rechargeInfoVo
     * @return {orderNo:"充值订单编号"}
     */
    @Override
    public Map<String, String> submitRecharge(RechargeInfoVo rechargeInfoVo) {
        Long userId = AuthContextHolder.getUserId();
        //1.创建充值对象
        RechargeInfo rechargeInfo = new RechargeInfo();
        rechargeInfo.setUserId(userId);
        rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_UNPAID);
        rechargeInfo.setRechargeAmount(rechargeInfoVo.getAmount());
        rechargeInfo.setPayWay(rechargeInfoVo.getPayWay());
        //充值订单编号| 形式="CZ"+年月日+雪花算法
        String orderNo = "CZ" + DateUtil.today().replaceAll("-", "") + IdUtil.getSnowflakeNextId();
        rechargeInfo.setOrderNo(orderNo);
        //2.保存充值记录
        rechargeInfoMapper.insert(rechargeInfo);
        //3. TODO 发送延迟消息关闭未支付充值记录

        Map<String, String> map = new HashMap<>();
        map.put("orderNo", orderNo);
        return map;
    }
}
